package com.lgd.warehousemanagement.Activity;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;

import android.util.Log;
import android.view.View;

import com.lgd.warehousemanagement.R;
import com.lgd.warehousemanagement.Utils.SerialportUtil.SerialInter;
import com.lgd.warehousemanagement.Utils.SerialportUtil.SerialManage;
import com.lgd.warehousemanagement.Utils.ToastUtils;
import com.lgd.warehousemanagement.databinding.ActivityDemoBinding;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.OutputStream;

import android_serialport_api.SerialPortUtils;


public class DemoActivity extends AppCompatActivity {
    ActivityDemoBinding demoBinding;

    private static final String TAG = "DemoActivity";
    private Handler handler;
    private Runnable runnable;
    private boolean isRunning = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        demoBinding = ActivityDemoBinding.inflate(getLayoutInflater());
        setContentView(demoBinding.getRoot());
        EventBus.getDefault().register(DemoActivity.this);

        SerialPortUtils serialPortUtils = new SerialPortUtils();
        serialPortUtils.openSerialPort(4);

        demoBinding.btnDemo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                System.out.println("点击了按钮");
                serialPortUtils.sendSerialPort("5500010000AA");
            }
        });


//        handler = new Handler(Looper.getMainLooper());
//            runnable = new Runnable() {
//                @Override
//                public void run() {
//
//
//                    Log.d(TAG, "run: ----持续 运行-----");
//                    if (isRunning) {
//                        handler.postDelayed(this, 500); // 每5秒发送一次
//                    }
//                }
//            };
//            // 开始发送信息
//            startSendingMessages();
    }


    //接收主板回传信息
    @SuppressLint("ResourceType")
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(String info) {
        Log.d("接收到串口数据",info);
        demoBinding.tvDemo.setText(info);

        Log.e("event","----------------------");

    }

    private void startSendingMessages() {
        isRunning = true;
        handler.post(runnable);
    }

    private void stopSendingMessages() {
        isRunning = false;
        handler.removeCallbacks(runnable);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        stopSendingMessages(); // 确保在Activity销毁时停止发送消息
    }
}